package com.huhu.sys.filter;

import com.huhu.entity.Remote;
import com.huhu.global.SessionQueue;
import com.huhu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;

/**
 * Created by xuyi on 2016/9/7.
 */
public class RequestFilter extends HttpServlet implements Filter {

    @Autowired
    private UserService userService;

    public RequestFilter() {
        super();
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
            throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //添加Cookie
//        if (request.getCookies() == null || request.getCookies().length == 0) {
//            String sessionId = request.getSession().getId();
//            Cookie cookie = new Cookie("sessionId", sessionId);
//            cookie.setPath("/");
//            response.addCookie(cookie);
//        }

        String uri = request.getRequestURI();

        String sessionId = request.getSession().getId();

        if (!SessionQueue.deque.contains(sessionId)){
            SessionQueue.deque.add(sessionId);

//            String remoteAddr = request.getRemoteAddr();
            String remoteAddr = request.getHeader("X-Real-IP");
            String userAgent = request.getHeader("user-agent");

            Remote remote = new Remote();
            remote.setRemoteAddr(remoteAddr);
            remote.setUserAgent(userAgent);

            try {
                int flag = userService.insertRemote(remote);
            } catch (Exception e) {
                e.printStackTrace();
            }
            int size = SessionQueue.deque.size();
            if (size > 30) {
                SessionQueue.deque.removeFirst();
            }
        }

        if (uri.equals("/Tremain/") || uri.equals("/Tremain")) {
            response.sendRedirect("/Tremain/html/index.html");
            return;
        }

        chain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}
